package com.leetcode.partition5;

/**
 * @author `RKC`
 * @date 2021/10/4 9:34
 */
public class LC482秘钥格式化 {

    public static String licenseKeyFormatting(String s, int k) {
        if (k <= 0) return "";
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) != '-') {
                sb.append(s.charAt(i));
            }
        }
        for (int i = sb.length() - k; i > 0; i -= k) {
            sb.insert(i, '-');
        }
        return sb.toString().toUpperCase();
    }

    public static void main(String[] args) {
        String s = "2-5g-3-J";
        int k = 2;
//        String s = "5F3Z-2e-9-w";
//        int k = 4;
        System.out.println(licenseKeyFormatting(s, k));
    }

    private static String solution(String s, int k) {
        //有n个破折号，s就被分成了n+1部分
        StringBuilder sb = new StringBuilder();
        if (s.length() <= k) {
            appendToSb(s, sb);
            return sb.toString();
        }
        appendToSb(s, sb);
        int length = sb.toString().length();
        if (length % k == 0) {
            //刚好可以使每个部分都有相同数量的字符
            for (int i = k; i < sb.length(); i += k + 1) {
                sb.insert(i, '-');
            }
        } else {
            //不能够平方，先计算出第一部分和其余部分的字符数
            int first = length % k;
            sb.insert(first, '-');
            for (int i = first + k + 1; i < sb.length(); i += k + 1) {
                sb.insert(i, '-');
            }
        }
        return sb.toString();
    }

    private static void appendToSb(String s, StringBuilder sb) {
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == '-') continue;
            if (s.charAt(i) >= 'a' && s.charAt(i) <= 'z') sb.append((char) (s.charAt(i) - 32));
            else sb.append(s.charAt(i));
        }
    }
}
